<?php

namespace Service\Http\Controller;

use Service\AjaxModel\AjaxResponse;
use Service\Http\Exception\RestException;
use Service\Http\Request;

class TestController extends Controller
{
    /**
     * @throws RestException
     */
    public function index(Request $request): AjaxResponse
    {
        $user = $this->getUserObj($request);
        return AjaxResponse::success(['user' => $user['username'], 'admin' => $this->checkUserAdminRole($user)]);
    }

    /**
     * @throws RestException
     */
    public function upload(Request $request): AjaxResponse
    {
        $suffix = substr(strrchr($_FILES['img']['name'], '.'), 1);
        $md5_string = md5_file($_FILES['img']['tmp_name'], false);
        $new_file = "img/assets/$md5_string.$suffix";
        if (!move_uploaded_file($_FILES['img']['tmp_name'], $new_file)) {
            throw new RestException('文件上传失败');
        }
        return AjaxResponse::success(['file' => $new_file]);
    }
}
